//
//  RegisterTableViewCell.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/10.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit

// 登录成功回调
typealias MessageBlock = () -> Void

class RegisterTableViewCell: BaseTableViewCell,UITextFieldDelegate {

    @IBOutlet weak var titleImageView: UIImageView!//图片
    @IBOutlet weak var textField: UITextField!//输入框
    @IBOutlet weak var lineView: UIView!//底线
    @IBOutlet weak var errorButton: UIButton!//错误提示
    @IBOutlet weak var showHidePasswordButton: UIButton!//密码展示与隐藏
    @IBOutlet weak var codeView: UIView!//图片验证码View
    @IBOutlet weak var codeImageView: UIImageView!//图片验证码
    
    var viewModel:RegisterViewModel = RegisterViewModel.init()
    
    var codeImageViewClickBlock:MessageBlock?
    var errorFlagBlock:MessageBlock?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.selectedBackgroundView = UIView()
        self.selectedBackgroundView?.backgroundColor = UIColor.white
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    override func configure(_ entity: Any) {
        
        self.viewModel = entity as! RegisterViewModel
        self.titleImageView.image = UIImage.init(named: self.viewModel.imageTitle)
        self.textField.placeholder = self.viewModel.placeholder
        self.textField.text = self.viewModel.textFieldString
        
        self.errorButton.isHidden = !self.viewModel.isErrorFlag
        self.errorButton.setTitle(self.viewModel.errorMessage, for: UIControl.State.normal)
        self.lineView.backgroundColor = self.viewModel.isErrorFlag ? UIColor.init("FFA855") : UIColor.black.withAlphaComponent(0.1);
        self.showHidePasswordButton.isHidden = viewModel.caseType == .password ? false : true ;
        self.codeView.isHidden = self.viewModel.caseType == .verificationCode ? false : true ;
        
        self.textField.keyboardType = UIKeyboardType.default
        if self.viewModel.caseType == .phoneNumber {
            self.textField.keyboardType = UIKeyboardType.numberPad
        }
        self.textField.isSecureTextEntry = false
        if self.viewModel.caseType == .password {
            self.textField.isSecureTextEntry = true
        }
        if self.viewModel.caseType == .verificationCode {
            self.configureCodeImageView()
        }
    }
    
    func configureCodeImageView() {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.codeImageViewClick))
        self.codeImageView.isUserInteractionEnabled = true
        self.codeImageView.addGestureRecognizer(gesture)
    }
    
    // MARK: -- @objc func
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.viewModel.textFieldString = textField.text!
        if self.viewModel.caseType == .account {
            self.viewModel.isErrorFlag = !self.accountCheck()
            if self.errorFlagBlock != nil {
                self.errorFlagBlock!()
            }
        }else if self.viewModel.caseType == .password {
            self.viewModel.isErrorFlag = !self.passwordCheck()
            if self.errorFlagBlock != nil {
                self.errorFlagBlock!()
            }
        }else if self.viewModel.caseType == .phoneNumber {
            self.viewModel.isErrorFlag = !self.phoneNumberCheck()
            if self.errorFlagBlock != nil {
                self.errorFlagBlock!()
            }
        }
    }
    
    @IBAction func showHidePasswordClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        self.textField.isSecureTextEntry = !self.textField.isSecureTextEntry
        ToolHelper.statisticsPage(pageName: "登录/注册-密码-显示密码")
        print("loginShowPassword")
    }
    
    @objc func codeImageViewClick() {
        if self.codeImageViewClickBlock != nil {
            self.codeImageViewClickBlock!()
        }
    }
    
    // 账号规则检测
    func accountCheck() -> Bool{
        let rule = "[a-zA-Z0-9]{4,11}"
        let result = self.checkCondition(text: self.textField.text!, withPattern: rule)
        return result
    }
    
    // 密码规则检测
    func passwordCheck() -> Bool{
        let rule = "^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9~=!/\\@#$`%^*/(/)_;:|/}/{[/?]></./,+/-]{6,16})$"
        let result = self.checkCondition(text: self.textField.text!, withPattern: rule)
        return result
    }
    
    // 手机号码位数检测 - 并不是手机号码检测
    func phoneNumberCheck() -> Bool{
        let result = self.textField.text!.count == 11
        return result
    }
    
    
    // 通用检测方法
    func checkCondition(text: String, withPattern: String) -> Bool {
        if let range = text.range(of: withPattern, options: .regularExpression){
            let subString = text.substring(with: range)
            return !text.isEmpty && subString == text
        }
        return false
    }
}
